'use strict'
import BaseComponent from '../../prototype/baseComponent'
import UserModel from '../../models/v2/users'
import UserInfoModel from '../../models/v2/userInfo'
import crypto from 'crypto'
import formidable from 'formidable'
import dtime from 'time-formater'
 class User extends BaseComponent {
    constructor() {
        super()
        this.login = this.login.bind(this)
        this.encryption = this.encryption.bind(this)
    }
    async login (req, res, next) {
        const capCode = req.cookies.cap;
        try {
            if (!capCode ) {
                console.log('验证码失效')
                res.send({
                    status: 0,
                    type: 'ERROR_CAPTCHA',
                    message: '验证码失效',
                    capCode: req.cookies.cap
                })
                return
            }
        } catch (err) {
            console.log(err)
        }
        const form = new formidable.IncomingForm();
        form.parse(req, async(err, fields, files) => {
            const {username, password, cap} = fields
            try {
                if(!username) {
                    throw new Error('用户名不能为空')
                } else if (!password) {
                    throw new Error('密码不能为空')
                } else if (!cap) {
                    throw new Error('验证码不能为空')
                }
            } catch (err) {
                console.log(err)
                res.send({
                    status: 0,
                    type: 'ERROR_QUERY',
                    message: err.message
                })
                return
            }
            if(capCode.toString() != cap) {
                res.send({
                    status: 0,
                    type: 'ERROR_CAPTCHA',
                    message: '验证码不正确',
                    cap: capCode.toString()
                })
                return
            }
            const newpassword = this.encryption(password)
            try {
                const user = await UserModel.findOne({username}, '-_id')
                if (!user) {
                    const user_id = await this.getId('user_id')
                    const register_time = dtime().format('YYYY-MM-DD HH:mm')
                    const newUser = {username, password:newpassword, user_id}
                    const newUserInfo = {username, user_id, id: user_id, register_time}
                    UserModel.create(newUser)
                    const createUser = new UserInfoModel(newUserInfo)
                    const userInfo = await createUser.save()
                    req.session.user_id = user_id
                    res.send(userInfo)
                } else if (user.password.toString() !== newpassword.toString()) {
                    console.log('用户登录密码错误')
                    res.send({
                        status: 0,
                        type: 'ERROR_PASSWORD',
                        message: '密码错误',
                    })
                    console.log('node')
                    return
                } else {
                    console.log('yes')
                    req.session.user_id = user.user_id
                    const userInfo = await UserInfoModel.findOne({user_id: user.user_id}, '-_id')
                    res.send(userInfo)
                }
            } catch (err) {
                console.log('用户登陆失败', err);
                res.send({
                    status: 0,
                    type: 'SAVE_USER_FAILED',
                    message: '登陆失败',
                })
            }
        })
    }
    async getInfo(req, res,next) {
        const sid = req.session.user_id
        const qid = req.query.user_id
        const user_id = sid || qid
        if(!user_id || !Number(user_id)) {
            console.log('获取用户信息的参数user_id无效', user_id)
            res.send({
                status: 0,
                type: 'GET_USER_INFO_FAIELD',
                message: '通过session获取用户信息失败',
            })
            return
        }
        try {
            const userInfo = await UserInfoModel.findOne({user_id}, '-_id')
            res.send(userInfo)
        } catch (err) {
            console.log('通过session获取用户信息失败', err);
            res.send({
                status: 0,
                type: 'GET_USER_INFO_FAIELD',
                message: '通过session获取用户信息失败',
            })
        }
    }
    async getUserList(req, res, next) {
        try {
            const userList = await UserInfoModel.find({}, '-_id');
            res.send(userList)
        } catch (err) {
            console.log('通过用户ID获取用户信息失败', err);
            res.send({
                status: 0,
                type: 'GET_USER_INFO_FAIELD',
                message: '通过用户ID获取用户信息失败',
            })
        }
    }
     async getInfoById(req, res, next){
         const user_id = req.params.user_id;
         if (!user_id || !Number(user_id)) {
             console.log('通过ID获取用户信息失败')
             res.send({
                 status: 0,
                 type: 'GET_USER_INFO_FAIELD',
                 message: '通过用户ID获取用户信息失败',
             })
             return
         }
         try{
             const userinfo = await UserInfoModel.findOne({user_id}, '-_id');
             res.send(userinfo)
         }catch(err){
             console.log('通过用户ID获取用户信息失败', err);
             res.send({
                 status: 0,
                 type: 'GET_USER_INFO_FAIELD',
                 message: '通过用户ID获取用户信息失败',
             })
         }
     }
     async signout(req, res, next) {
         delete req.session.user_id
         res.send({
             status: 1,
             message: '退出成功'
         })
     }
    encryption(password) {
        const newpassword = this.Md5(password).substr(2, 7) + this.Md5(password)
        return newpassword
    }
    Md5(password) {
        const md5 = crypto.createHash('md5')
        return md5.update(password).digest('base64')
    }


 }

 export default new User();